<?php

define('PATH_ROOT', dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "app" . DIRECTORY_SEPARATOR . "webroot" . DIRECTORY_SEPARATOR);
define('PHPMAILER', dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "app" . DIRECTORY_SEPARATOR . "Vendor" . DIRECTORY_SEPARATOR . "PHPMailer" . DIRECTORY_SEPARATOR);

/**
 * 
 */
function getFolderName($string) {
    $string = str_replace(' ', '-', $string);
    $folder = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
    if (!file_exists(PATH_ROOT . 'video' . DIRECTORY_SEPARATOR . $folder)){
        $old = umask(0);
        mkdir(PATH_ROOT . 'video' . DIRECTORY_SEPARATOR . $folder, 0777);
        umask($old);
    }
    return $folder;
}

/**
 * 
 */
function getNextFile($code, $db) {
    $row = $db->row('SELECT count(Id) as count FROM records WHERE Id = :Id', array('Id' => $code));
    return isset($row['count']) ? $row['count'] + 1 : 1;
}

/**
 *
 * @param type $url
 * @return type 
 */
function pingCammera($url) {
    if ($url == NULL)
        return false;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    //var_dump(($contentType && strpos($contentType,'multipart') !== false));echo "<br>";
    curl_close($ch);
    if ($contentType && strpos($contentType, 'multipart') !== false) {
        return true;
    } else {
        return false;
    }
}

function sendMail($to, $params, $body, $from) {
    //get body
    if (is_array($params)) {
        foreach ($params as $key => $value) {
            $body = str_replace("%%" . $key . "%%", $value, $body);
        }
    }
    //var_dump($body);die;
    $autoLoad = PHPMAILER . 'PHPMailer.php';
    require_once $autoLoad;
    $mail = new PHPMailer();
    $mail->IsHTML(true);/*
    $mail->IsSMTP();
    $mail->SMTPDebug = false;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'ssl';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 465;
    $mail->Username = "hungvu2803@gmail.com";
    $mail->Password = "tuhung11000";*/
    $mail->setFrom($from, 'cakephp test');
    $mail->Subject = "the cameras don't work";
    $mail->Body = $body;
    //$mail->AddAddress($to);
    $mail->AddAddress($from);
    $mail->Send();
}
